<template>
  <div class="training-page">
    <el-card shadow="never" v-loading="loading" element-loading-text="加载中...">
      <div slot="header" class="card-header">
        <div>
          <h3 class="title">实训成绩列表</h3>
          <p class="subtitle">所有焊接实训项目及成绩</p>
        </div>
        
        <div class="header-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索实训项目..."
            prefix-icon="el-icon-search"
            size="small"
            clearable
            style="width: 200px;"
            @keyup.enter.native="handleSearch"
          ></el-input>

          <el-select
            v-model="filterStatus"
            placeholder="全部状态"
            size="small"
            clearable
            style="width: 120px;"
          >
            <el-option label="全部状态" value="all"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="进行中" value="in-progress"></el-option>
            <el-option label="未开始" value="not-started"></el-option>
          </el-select>

          <el-button 
            type="primary" 
            size="small"
            icon="el-icon-search"
            @click="handleSearch"
          >
            搜索
          </el-button>

          <el-button 
            size="small"
            icon="el-icon-refresh"
            @click="handleReset"
          >
            重置
          </el-button>
        </div>
      </div>

      <el-table 
        :data="filteredTrainingList" 
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column label="训练项目" min-width="180">
          <template slot-scope="scope">
            <span style="font-weight: 500;">{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.status)" 
              size="small"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="开始时间" width="120" prop="startDate"></el-table-column>

        <el-table-column label="结束时间" width="120" prop="endDate"></el-table-column>

        <el-table-column label="成绩" width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.score !== null" style="font-weight: 500;">
              {{ scope.row.score }}
            </span>
            <span v-else style="color: #C0C4CC">-</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="right">
          <template slot-scope="scope">
            <!-- 已完成状态：可点击的查看回放和成绩报告 -->
            <template v-if="scope.row.status === '已完成'">
              <el-button 
                type="text" 
                size="small"
                @click="viewReplay(scope.row)"
              >
                查看回放
              </el-button>
              <el-button 
                type="text" 
                size="small"
                @click="downloadReport(scope.row)"
              >
                成绩报告
              </el-button>
            </template>
            
            <!-- 进行中和未开始状态：不可点击的查看回放和成绩报告 -->
            <template v-else>
              <span style="color: #DCDFE6; font-size: 12px;">
                查看回放
              </span>
              <span style="color: #DCDFE6; font-size: 12px; margin-left: 8px;">
                成绩报告
              </span>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <div class="pagination-info">
          显示 {{ (currentPage - 1) * pageSize + 1 }} 至 {{ Math.min(currentPage * pageSize, totalTrainings) }} 条，共 {{ totalTrainings }} 条
        </div>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalTrainings"
          :page-size="pageSize"
          :current-page.sync="currentPage"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Training',
  data() {
    return {
      searchKeyword: '',
      filterStatus: 'all',
      currentPage: 1,
      pageSize: 10,
      totalTrainings: 0,
      allTrainingList: [],
      loading: false
    }
  },
  watch: {
    currentPage() {
      this.getScoreList()
    },
    filterStatus() {
      this.currentPage = 1
      this.getScoreList()
    }
  },
  mounted() {
    this.getScoreList()
  },
  computed: {
    filteredTrainingList() {
      // 关键词搜索 - 前端过滤
      let list = this.allTrainingList
      
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        list = list.filter(item => 
          item.name.toLowerCase().includes(keyword)
        )
      }
      
      return list
    }
  },
  methods: {
    // 获取虚拟教室成绩列表
    async getScoreList() {
      try {
        this.loading = true
        
        // 后端期望数字: 1=已完成, 0=进行中
        // 前端 filterStatus: 'all'/'completed'/'in-progress'/'not-started'
        let statusParam = undefined
        if (this.filterStatus === 'completed') {
          statusParam = 1 // 已完成
        } else if (this.filterStatus === 'in-progress') {
          statusParam = 0 // 进行中
        }
        // 'all' 或 'not-started' 不传 status 参数（查询全部）
        
        const res = await this.$api.virtualClassroom.getScoreList({
          status: statusParam,
          page: this.currentPage,
          page_size: this.pageSize
        })
        
        
        // 后端返回: { data: [...], pagination: {total, page, page_size, last_page} }
        // VirtualClassroom 字段: id, project_name, status, score, end_time
        this.allTrainingList = (res.data || []).map(item => ({
          id: item.id,
          name: item.project_name, // 后端字段是 project_name
          status: this.mapStatus(item.status),
          startDate: '-', // 后端未返回 start_date
          endDate: item.end_time || '-', // 后端返回 end_time
          score: item.score
        }))
        
        this.totalTrainings = res.pagination?.total || 0
        
      } catch (error) {
        this.$message.error('获取实训成绩列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 映射状态: 后端返回数字 1=已完成, 0=进行中
    mapStatus(status) {
      // 后端实际返回的是数字
      if (status === 1) return '已完成'
      if (status === 0) return '进行中'
      
      // 兼容字符串格式（如果后端改为字符串）
      const statusMap = {
        'completed': '已完成',
        'in_progress': '进行中',
        'not_started': '未开始',
        1: '已完成',
        0: '进行中'
      }
      return statusMap[status] || '未开始'
    },
    
    handleSearch() {
      this.currentPage = 1
      this.getScoreList()
    },
    handleReset() {
      this.searchKeyword = ''
      this.filterStatus = 'all'
      this.currentPage = 1
      this.$message.success('已重置搜索条件')
    },
    getStatusTagType(status) {
      const statusMap = {
        '已完成': 'success',
        '进行中': '',
        '未开始': 'info'
      }
      return statusMap[status] || ''
    },
    viewReplay(row) {
      this.$message.info(`查看 ${row.name} 的实训回放`)
    },
    continueTraining(row) {
      this.$message.info(`继续 ${row.name}`)
    },
    prepareTraining(row) {
      this.$message.info(`准备 ${row.name}`)
    },
    downloadReport(row) {
      this.$message.success(`正在下载 ${row.name} 的成绩报告...`)
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #304156;
  margin: 0 0 4px 0;
}

.subtitle {
  font-size: 13px;
  color: #86909C;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions .el-input {
  width: 200px;
}

.header-actions .el-select {
  width: 120px;
}

.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #EBEEF5;
}

.pagination-info {
  font-size: 13px;
  color: #86909C;
}

@media (max-width: 992px) {
  .card-header {
    flex-direction: column;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    flex-direction: column;
  }

  .header-actions .el-input,
  .header-actions .el-select,
  .header-actions .el-button {
    width: 100% !important;
  }
  
  .pagination-wrapper {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
